﻿<template>
  <div class="container a2cbox" style="width:99%;margin-top:-25px;">
    <!-- 查询条件 -->
    <div class="query-box query-boxstudent">
      <el-form :model="queryBox" status-icon ref="queryBox">
        <el-row>
          <!-- <el-col :span="4">
            <el-form-item label prop="name">
              <el-input v-model="queryBox.signRep" placeholder="大区经理">
                <template slot="prepend">大区经理</template>
              </el-input>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="4">
            <el-form-item label prop="phone">
              <el-input v-model="queryBox.area" placeholder="地区">
                <template slot="prepend">地区</template>
              </el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="4">
            <el-form-item label prop="school">
              <el-input v-model="queryBox.name" placeholder="分中心名称">
                <template slot="prepend">分中心名称</template>
              </el-input>
            </el-form-item>
          </el-col>
            <el-col :span="7">
            <el-row class="area">
              <el-col :span="4">
                <span class="city-title">地区：</span>
              </el-col>
              <el-col :span="17" style="margin-left:-1px">
                <el-form-item label prop="area">
                  <el-cascader
                    clearable
                    @change="addressChange"
                    size="large"
                    :options="options"
                    v-model="selectedOptions"
                  ></el-cascader>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="7" style="margin-left:0">
            <el-tag
              style="float:left;margin-top: 4px;"
                    v-for="tag in diqutags3"
                    :key="tag.key"
                    closable
                    @close='tagsClose(tag)'
                    :type="tag.type">
                    {{tag.value}}
                  </el-tag>
          </el-col>
            </el-row>
          </el-col>
          <!-- <el-col :span="4">
            <div class="depart-box">
              <div class="slect-title">合同类型</div>
              <el-select clearable filterable v-model="queryBox.contractType">
                <el-option
                  v-for="item in contractType_option"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
            </div>
          </el-col> -->
        </el-row>
        <!-- <el-row>
          <el-col :span="4">
            <div class="depart-box">
              <div class="slect-title">独家/非独家</div>
              <el-select clearable filterable v-model="queryBox.isSole">
                <el-option
                  v-for="item in isSoleOption"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
            </div>
          </el-col>
        </el-row>  -->
      </el-form>
      <div class="from-btns">
        <kt-button
          :label="$t('action.reset')"
          perms="true"
          type="primary"
          @click="reset('queryBox')"
        />
        <kt-button :label="$t('action.search')" perms="true" type="primary" @click="search"/>
      </div>
    </div>
    <div class="fr">
      <kt-button
        :label="$t('action.download-tmpl')"
        type="primary"
        perms="mycustomer:2Ccenter:download"
        @click="downloadTmpl"
      ></kt-button>
      <kt-button
        :label="$t('action.batchimport')"
        type="primary"
        perms="mycustomer:2Ccenter:batchimport"
        @click="customerManagerImport"
      ></kt-button>

    </div>
    <!--表格内容栏-->
    <div class="btn">
      <Crm-table
        
        class="table-width"
        @handleSee='handleSee'
        width="400"
        permsEdit='mycustomer:2Ccenter:Edit'
        :data="pageResult"
        :columns="columns"
        :loading="loading"
        @findPage="findPage"
      ></Crm-table>
      <!-- 表格字段 twoCcenter -->
    </div>

    <!--导入-->
    <el-dialog
      :title="'批量导入'"
      width="30%"
      :visible.sync="uploadOem"
      :close-on-click-modal="false"
    >
      <el-form :model="form">
        <el-form-item>
          <el-upload
            ref="uploadExcel"
            :action="uploadUrl"
            :limit="limitNum"
            :auto-upload="false"
            accept=".xls"
            :before-upload="beforeUploadFile"
            :on-change="fileChange"
            :on-exceed="exceedFile"
            :on-success="handleSuccess"
            :on-error="handleError"
            :file-list="fileList"
            :on-remove="handleRemove"
          >
            <el-button size="small" plain>选择文件上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传xls(Excel97-2004)文件
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="uploadOem = false">{{
          $t("action.cancel")
        }}</el-button>
        <el-button size="mini" type="primary" @click.native="uploadFile">{{
          $t("立即上传")
        }}</el-button>
      </div>
    </el-dialog>
    <!--导入-->
    <el-dialog
      :title="'独家/非独家'"
      width="25%"
      :visible.sync="editType"
      :close-on-click-modal="false"
    >
    <span>独家/非独家: </span>
    <el-select clearable filterable v-model="isSoleType">
        <el-option
          v-for="item in isSoleOption"
          :key="item.lable"
          :label="item.value"
          :value="item.key"
        ></el-option>
      </el-select>
      <div style="margin-top:20px;">
        <kt-button :label="$t('提交')" perms="true" type="primary" @click="updateIsSole"/>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import PopupTreeInput from "@/components/PopupTreeInput";
import KtButton from "@/views/Core/KtButton";
import CrmTable from "@/views/Core/CrmTable";
import CrmSwitch from "@/views/Core/CrmSwitch";
import { CodeToText } from "element-china-area-data";
import { baseUrl } from "@/utils/global";
import Cookies from "js-cookie";
import { regionData } from "element-china-area-data";
import { regionDataPlus } from "element-china-area-data";
import axios from "axios";
import store from "@/store";
import { isMobile } from "@/utils/validate";
import { mapActions } from "vuex";
import CrmPermsBox from "@/views/Core/Crmpermsbox";
// 索要
import Askingfor from "@/views/Core/Askingfor";

export default {
  name: "Student",
  components: {
    PopupTreeInput,
    CrmTable,
    KtButton,
    CrmSwitch,
    CrmPermsBox,
    Askingfor
  },
  data() {
    return {
    loading:false,
      queryBox: {
        contractType:'',
        signRep:'',
        area:'',
        isSole:'',
        name:''
      },
      width: 200,
      columns: [
        { type: "index", label: "序号", minWidth: 50 },
        { prop: "name", label: "分中心名称", minWidth: 120 },
        { prop: "area", label: "地区", minWidth: 200 },
        { prop: "contractEndDay", label: "合同到期时间", minWidth: 120 },
      ],
      pageResult: {
        content: []
      },
      uploadOem: false, //文件上传
      limitNum: 1, //上传最大个数
      form: {
        file: ""
      },
      //   地区
      options: regionData,
      selectedOptions: [],
      baseUrl: baseUrl,
      fileList: [],
      uploadUrl: baseUrl + "/file/upload", //文件上传地址
      downloadTmplUrl: baseUrl + "/template/studentImportTemplate.xlsx", //模板下载地址
      contractType_option:[],
      editType:false,
      isSoleOption:[
        {
            "key":"1",
            "value":"独家"
        },
        {
            "key":"2",
            "value":"非独家"
        },
        {
            "key":"0",
            "value":""
        }
      ],
      isSoleType:'',
      diqutags:[],
      diqutags2: [],
      diqutags3: [],
      diqutagsADD: [],
      diqutags2ADD: [],
      diqutags3ADD: [],
      selectedOptionsAdd: [],
      oldEidtAreaCode: []
    };
  },
  methods: {
    // 搜索
    search() {
      this.loading = true;
      
      
      this.pageRequest.pageNum = 1;
      this.findPage(null);
    },
    getDown(){
      this.contractType_option = JSON.parse(
        localStorage.getItem("contractTypeOption")
      );
    },
    // 获取分页数据
    findPage: function(data) {
      if (data !== null) {
        this.loading = true;
        this.pageRequest = data.pageRequest;
      }
      this.queryBox.pageSize = this.pageRequest.pageSize;
      this.queryBox.pageNum = this.pageRequest.pageNum;
      this.queryBox.businessType=1
      this.pageRequest = Object.assign({}, this.pageRequest, this.queryBox,);
      this.$api.student
        .tocBranchInfo(this.pageRequest)
        .then(res => {
          let content = { content: res.branchCenterInfoList, totalSize: res.total };
          this.pageResult = content;
          
          this.pageResult.content.forEach(item => {
            item.startDate=/\d{4}-\d{1,2}-\d{1,2}/g.exec(item.startDate)
            item.stopDate=/\d{4}-\d{1,2}-\d{1,2}/g.exec(item.stopDate)
            if(item.startDate){
              item.contractEndDay=item.startDate+'--'+item.stopDate
            }
            this.contractType_option.forEach(type_item => {
                if (type_item.key == item.contractType) {
                  item.leixing = type_item.value;
                }
              });

            switch(item.isSole){
              case '1':item.isSoleStr='独家'
              break
              case '2':item.isSoleStr='非独家'
              break
              case '0':item.isSoleStr=''
              break
            }
          });
          this.loading = false;
        })
        .then(data != null ? data.callback : "");
    },

    // 重置
    reset(queryBox) {
      this.$refs.queryBox.resetFields();
      this.queryBox.signRep=''
      this.queryBox.area=''
      this.queryBox.name=''
      this.queryBox.areaCode = "";
      this.selectedOptions = [];
      this.diqutags = [];
      this.diqutags2 = [];
      this.diqutags3 = [];
      this.queryBox.contractType=''
      this.queryBox.isSole=''
      this.pageRequest.pageNum = 1;
      this.findPage(null);
    },
    // 批量导入 
    customerManagerImport: function() {
      this.uploadOem = true;
      if (this.form.file != "") {
        this.$refs.uploadExcel.clearFiles();
        this.form.file = "";
      }
    },
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$notify.warning({
        title: "警告",
        message: `只能选择 ${
          this.limitNum
        } 个文件，当前共选择了 ${files.length + fileList.length} 个`
      });
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {
      this.form.file = file.raw;
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      let size = file.size / 1024 / 1024;
      if (extension !== "xls") {
        this.$notify.warning({
          title: "警告",
          message: `只能上传Excel97-2004（即后缀是.xls）的文件`
        });
      }
      1;
    },
    // 文件上传成功时的钩子
    handleSuccess(res, file, fileList) {
      this.$refs.uploadExcel.clearFiles();
      this.form.file = "";
      this.$notify.success({
        title: "成功",
        message: `文件上传成功,数据处理中,稍后在我的消息中查看！`
      });
    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$notify.error({
        title: "错误",
        message: `文件上传失败`
      });
    },
    uploadFile() {
      let formData = new FormData();
      formData.append("file", this.form.file);
      axios
        .post(this.uploadUrl, formData, {
          "Content-Type": "multipart/form-data"
        })
        .then(res => {
          if (res.data.result == 1) {
            this.handleSuccess();
            let path = res.data.fileUrl;
            this.$api.student
              .importTocBranchInfo({ path: path })
              .then(res => {
                this.uploadOem = false;
                this.findPage(null);
              });
          } else {
            this.handleError();
          }
        });
    },
   // 删除上传列表操作
    handleRemove(file, fileList) {
      this.form.file = "";
    },
     // 下载模板
    downloadTmpl() {
      this.get2CStuTempl();
    },
    handleSee(params){
      this.editType=true
      this.soleId=params.row.id
    },
    updateIsSole(id){
      this.$api.student.updateIsSole({id:this.soleId,isSole:this.isSoleType}).then(res=>{
        if(res.result==1){
          this.$message({
              message: res.msg,
              type: "success"
          });
          this.editType=false
          this.isSoleType=''
          this.findPage(null)
        }else{
          this.$message({
            message: res.msg,
            type: "error"
          });
        }
      })
    },
    addressChange(params) {
      // 判断用户是否点击清空
      if (params.length == 0) {
        (this.diqutags.length = 0),
          (this.diqutags3.length = 0),
          (this.queryBox.length = 0),
          (this.queryBox.areaCode = "");
      } else {
        this.queryBox.areaCode = params[2];
        this.diqutags.push(this.queryBox.areaCode);
        let newarry = [];
        // 追加属性
        for (let i = 0; i < this.diqutags.length; i++) {
          let j = {};
          j.key = this.diqutags[i];
          newarry.push(j);
        }
        this.diqutags2 = newarry;
        this.diqutags2.forEach(item => {
          item.key = item.key;
          item.value = CodeToText[item.key];
        });
        // 去重
        let hash = {};
        const data2 = this.diqutags2.reduce((preVal, curVal) => {
          hash[curVal.key]
            ? ""
            : (hash[curVal.key] = true && preVal.push(curVal));
          return preVal;
        }, []);
        this.diqutags3 = data2;
        // 查询数据重组
        this.queryBox.areaCode = this.diqutags.join(",");
      }
      // this.selectedOptions=[]
    },
    addressChangeADD(params) {
      if (params.length == 0) {
        this.diqutags3ADD.length = 0;
        this.diqutags2ADD.length = 0;
        this.diqutagsADD.length = 0;
        this.dataFormAdd.areaCode = "";
      } else {
        this.diqutagsADD.push(params[2], ...this.oldEidtAreaCode);
        let newarry = [];

        // 追加属性
        for (let i = 0; i < this.diqutagsADD.length; i++) {
          let j = {};
          j.key = this.diqutagsADD[i];
          newarry.push(j);
        }
        this.diqutagsADD=Array.from(new Set(this.diqutagsADD))
        this.diqutags2ADD = newarry;
        this.diqutags2ADD.forEach(item => {
          item.key = item.key;
          item.value = CodeToText[item.key];
        });
        // 去重
        let hash = {};
        const data2 = this.diqutags2ADD.reduce((preVal, curVal) => {
          hash[curVal.key]
            ? ""
            : (hash[curVal.key] = true && preVal.push(curVal));
          return preVal;
        }, []);
        this.diqutags3ADD = data2;
        this.queryBox.areaCode = this.diqutagsADD.join(",");
      }
      // this.selectedOptions=[]
    },
    tagsClose(params) {
      // this.diqutags3.splice(params, 1);
      // this.diqutags.splice(this.diqutags.findIndex(v => v == params.key), 1);
      this.diqutags3.splice(
        this.diqutags3.findIndex(item => item.key === params.key),
        1
      );
      this.diqutags.splice(this.diqutags.findIndex(v => v == params.key), 1);
      this.queryBox.areaCode = this.diqutags.join(",");
      if (this.diqutags.length == 0) {
        this.selectedOptions = [];
      }
    },
    // 新增地区关闭
    tagsCloseADD(params) {
      this.diqutags3ADD.splice(
        this.diqutags3ADD.findIndex(item => item.key === params.key),
        1
      );
      this.diqutagsADD = this.oldEidtAreaCode;
      this.diqutagsADD.splice(
        this.diqutagsADD.findIndex(item => item === params.key),
        1
      );
      this.dataForm.areaCode = this.diqutagsADD.join(",");
      if (this.diqutagsADD.length == 0) {
        this.selectedOptions = [];
      }
    }
  },

  mounted() {
    this.getDown()
    this.findPage(null);
  },

};
</script>
<style >
@import url("../../assets/queryBox.css");
</style>
<style lang='scss'>
.a2cbox{
  
   .el-table--mini th{
    padding: 5px 0!important;
   }
   .btn .el-table--mini td{
 padding: 5px 0!important;
   }
}
</style>
